package org.txazo.music.commons.mp3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class AlbumSearcher {

	public static final String KOGOU_ALBUM_SEARCH_URL = "http://www.kugou.com/yueku/app/search.php";
	public static final String KOGOU_ALBUM_SEARCH_WORD = "?word=";
	public static final String KOGOU_ALBUM_SEARCH_OTHERS = "&page=1&t=1&cmd=1";

	public static String getURL(String word) {
		StringBuilder sb = new StringBuilder(150);
		sb.append(KOGOU_ALBUM_SEARCH_URL);
		sb.append(KOGOU_ALBUM_SEARCH_WORD);
		sb.append(word);
		sb.append(KOGOU_ALBUM_SEARCH_OTHERS);
		return sb.toString();
	}

	public static List<Album> getAlbumList(String word) {
		List<Album> list = new ArrayList<Album>();

		String data = getAlbum(word);
		data = data.substring(data.indexOf('[') + 2, data.indexOf(']') - 1);
		String[] albums = data.split("\\}\\,\\{");

		for (String album : albums) {
			System.out.println(album);
			list.add(convertJSONToAlbum(album));
		}

		return list;
	}

	public static Album convertJSONToAlbum(String json) {
		Album album = new Album();

		String[] datas = json.split("\\,");
		for (String data : datas) {
			String[] params = data.split(":");
			params[0] = cutQuote(params[0]);
			params[1] = cutQuote(params[1]);
			if (params[0].equals("publish_time")) {
				album.setPublishTime(params[1]);
			} else if (params[0].equals("albumname")) {
				album.setAlbum(params[1]);
			} else if (params[0].equals("title")) {
				album.setArtist(params[1]);
			} else if (params[0].equals("company")) {
				album.setCompany(params[1]);
			} else if (params[0].equals("img")) {
				album.setImgURL(params[1] + ":" + params[2]);
			} else if (params[0].equals("intro")) {
				album.setDescription(params[1]);
			}
		}

		return album;
	}

	public static String cutQuote(String str) {
		return str.replace("\"", "");
	}

	public static String getAlbum(String word) {
		String data = null;
		BufferedReader br = null;
		try {
			URL url = new URL(getURL(word));
			br = new BufferedReader(new InputStreamReader(url.openStream()));

			String temp = null;
			while ((temp = br.readLine()) != null) {
				temp = temp.trim();
				if (temp.startsWith("{\"status\"")) {
					data = temp;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return data;
	}

	public static void main(String[] args) {
		List<Album> list = getAlbumList("告别");
		for (Album album : list) {
			System.out.println(album);
		}
	}

}
